# -*- coding: utf-8 -*-

import urllib2, urllib, json
from saltops.settings import SALT_CFG
import datetime

salt = None

class SaltAPI(object):
    def __init__(self, url, username, password):
        ## 删除url末尾的'/'
        self.__url = url.rstrip('/')
        self.__user = username
        self.__password = password
        self.__token = self.saltLogin()

    def saltLogin(self):
        params = {
            'eauth': 'pam',
            'username': self.__user,
            'password': self.__password
        }
        reqBody = json.dumps(params)
        reqHeaders = {
            'Content-Type': 'application/json',            
            'X-Auth-Token': ''
        }
        url = self.__url + '/login'
        req = urllib2.Request(url, reqBody, reqHeaders)
        ## 返回值格式化
        result = json.loads(urllib2.urlopen(req).read())
        try: 
            token = result['return'][0]['token']
            return token
        except KeyError:
            raise KeyError

    def postRequest(self, params, path = '/'):
        url = self.__url + path
        reqHeaders = {
            'Content-Type': 'application/json',
    		'X-Auth-Token': self.__token
        }
        reqBody = json.dumps(params)
        req = urllib2.Request(url, reqBody, reqHeaders)
        result = urllib2.urlopen(req)
        result = json.loads(result.read())
        return result

def gen_jid():
    '''
    生成jid, 取自salt/utils/jid.py
    '''
    return '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())

def is_jid(jid):
    '''
    判断jid是否合法, 返回True/Fasle
    '''
    if not isinstance(jid, six.string_types):
        return False
    if len(jid) != 20:
        return False
    try:
        int(jid)
        return True
    except ValueError:
        return False

if salt == None:
    salt = SaltAPI(
        url = SALT_CFG['url'], 
        username = SALT_CFG['user'], 
        password = SALT_CFG['password']
    )
